package com.lmuse.xmr.foodspotting.db;

import com.lmuse.xmr.foodspotting.model.Recipe;
import com.lmuse.xmr.foodspotting.model.User;

import java.io.File;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadBatchListener;
import cn.bmob.v3.listener.UploadFileListener;

public class RecipePresenterImpl implements Contract.RecipePresenter {

    private Contract.RecipeView recipeView;

    public RecipePresenterImpl(Contract.RecipeView recipeView) {
        this.recipeView = recipeView;
    }

    @Override
    public void uploadImgFile(String filePath) {
        final BmobFile bmobFile = new BmobFile(new File(filePath));
        bmobFile.uploadblock(new UploadFileListener() {

            @Override
            public void done(BmobException e) {
                if(e==null){
                    //bmobFile.getFileUrl()--返回的上传文件的完整地址
                    recipeView.onUploadImgSuccess(bmobFile);
                }else{
                    String msg = "上传封面图失败" + e.toString();
                    recipeView.onUploadImgFailed(msg);
                }
            }

            @Override
            public void onProgress(Integer value) {
                // 返回的上传进度（百分比）
                recipeView.onUploadingImg(value);
            }
        });
    }

    @Override
    public void uploadImgFile(String[] filePaths) {

        final String[] filePath = filePaths;
        BmobFile.uploadBatch(filePaths, new UploadBatchListener() {

            @Override
            public void onSuccess(List<BmobFile> files,List<String> urls) {
                //1、files-上传完成后的BmobFile集合，方便对上传后的数据进行操作，例如可以将该文件保存到表中
                //2、urls-上传文件的完整url地址
                if(urls.size()==filePath.length){//如果数量相等，则代表文件全部上传完成
                    recipeView.onUploadImgSuccess(urls);
                }
            }

            @Override
            public void onError(int statuscode, String errormsg) {
                String msg = "上传内容失败！错误码为：" + statuscode + "错误信息为：" + errormsg;
                recipeView.onUploadImgFailed(msg);
            }

            @Override
            public void onProgress(int curIndex, int curPercent, int total,int totalPercent) {
                recipeView.onUploadingImg(curIndex, curPercent, total, totalPercent);
            }
        });
    }

    @Override
    public void addRecipe(String title, String coverUrl, String label, String content) {
        User userCache = BmobUser.getCurrentUser(User.class);
        Recipe recipe = new Recipe();
        //不能调用setObjectId("")方法
        recipe.setTitle(title);
        recipe.setCoverUrl(coverUrl);
        recipe.setLabel(label);
        recipe.setContent(content);
        recipe.setAuthor(userCache);
        recipe.save(new SaveListener<String>() {

            @Override
            public void done(String objectId, BmobException e) {
                if(e==null){
                    recipeView.onAddRecipeSuccess();
                }else{
                    recipeView.onAddRecipeFailed(e.toString());
                }
            }
        });
    }

    @Override
    public void queryRecipe(String rowName, String condition, int limit, int page) {
        if (rowName == "objectId") {
            BmobQuery<Recipe> query = new BmobQuery<Recipe>();
            query.getObject(condition, new QueryListener<Recipe>() {

                @Override
                public void done(Recipe object, BmobException e) {
                    if(e==null){
                        recipeView.onQueryRecipeSuccess(object);
                    }else{
                        recipeView.onQueryRecipeFailed(e.toString());
                    }
                }

            });
        }else {
            BmobQuery<Recipe> query = new BmobQuery<Recipe>();
            query.addWhereEqualTo(rowName, condition);
            query.setSkip(limit * page);
            //默认返回10条数据
            query.setLimit(limit);
            query.findObjects(new FindListener<Recipe>() {
                @Override
                public void done(List<Recipe> object, BmobException e) {
                    if(e==null){
                        recipeView.onQueryRecipeSuccess(object);
                    }else{
                        recipeView.onQueryRecipeFailed(e.toString());
                    }
                }
            });
        }
    }

    @Override
    public void queryRecipe(String rowName, String condition, int limit) {
        if (rowName == "objectId") {
            BmobQuery<Recipe> query = new BmobQuery<Recipe>();
            query.getObject(condition, new QueryListener<Recipe>() {

                @Override
                public void done(Recipe object, BmobException e) {
                    if(e==null){
                        recipeView.onQueryRecipeSuccess(object);
                    }else{
                        recipeView.onQueryRecipeFailed(e.toString());
                    }
                }

            });
        }else {
            BmobQuery<Recipe> query = new BmobQuery<Recipe>();
            query.addWhereEqualTo(rowName, condition);
            //默认返回10条数据
            query.setLimit(limit);
            query.findObjects(new FindListener<Recipe>() {
                @Override
                public void done(List<Recipe> object, BmobException e) {
                    if(e==null){
                        recipeView.onQueryRecipeSuccess(object);
                    }else{
                        recipeView.onQueryRecipeFailed(e.toString());
                    }
                }
            });
        }
    }

    @Override
    public void queryByKey(String rowName) {
        BmobQuery<Recipe> bmobQuery = new BmobQuery<Recipe>();
        bmobQuery.addQueryKeys(rowName);
        bmobQuery.findObjects(new FindListener<Recipe>() {
            @Override
            public void done(List<Recipe> object, BmobException e) {
                if(e==null){
                    //注意：这里的Recipe对象中只有指定列的数据。
                    recipeView.onQueryKeySuccess(object);
                }else{
                    recipeView.onQueryKeyFailed(e.toString());
                }
            }
        });
    }

    @Override
    public void deleteRecipe(String objectId) {
        Recipe recipe = new Recipe();
        recipe.setObjectId(objectId);
        recipe.delete(new UpdateListener() {

            @Override
            public void done(BmobException e) {
                if(e==null){
                    recipeView.onDeleteRecipeSuccess();
                }else{
                    recipeView.onDeleteRecipeFailed(e.toString());
                }
            }
        });
    }

    @Override
    public void onDetach() {

    }
}
